package com.tan.androidtest.io;

import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tan.androidtest.R;
import com.tan.androidtest.base.BaseActivity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 测试文件的IO操作
 */

public class TestFileIOActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvTest;
    private TextView mTvCopy;
    private TextView mTvChannel;
    private ProgressBar mPbTest;


    @Override
    public int initLayoutId() {
        return R.layout.activity_test_file_io_layout;
    }

    @Override
    public void initTitle(TextView tv_bar_left, TextView tv_bar_title, TextView tv_bar_right) {
        tv_bar_title.setText("测试File的IO操作");
    }

    @Override
    public void initView() {
        mTvTest = findViewById(R.id.tv_test);
        mTvTest.setOnClickListener(this);
        mTvCopy = findViewById(R.id.tv_copy);
        mTvCopy.setOnClickListener(this);
        mTvChannel = findViewById(R.id.tv_channel);
        mTvChannel.setOnClickListener(this);
        mPbTest = findViewById(R.id.pb_test);
    }

    @Override
    public void initData() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_test: {
                writeToFile();
                break;
            }
            case R.id.tv_copy: {
                new Thread() {

                    @Override
                    public void run() {
                        Log.i("==--", "时间: " + copyFileByStream());
                    }
                }.start();
                break;
            }
            case R.id.tv_channel: {
                new Thread() {

                    @Override
                    public void run() {
                        Log.i("==--", "时间1: " + copyFileByBufferStream());
                    }
                }.start();
                break;
            }
        }
    }

    /**
     * 使用FileWriter字符流
     */
    private void writeToFile() {
        FileWriter writer = null;
        String fileName = Environment.getExternalStorageDirectory() + File.separator + "demo.txt";
        Log.i("==--", fileName);
        try {
            writer = new FileWriter(fileName);
            writer.write("112233");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //如果前面发生异常，那么是无法产生writer对象的
            //因此要做出判断，以免发生空指针异常
            if (writer != null) {
                try {
                    //关闭流资源，需要再次捕捉异常
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 利用字节流复制二进制文件
     */
    private int lastPercent = 0;

    private long copyFileByStream() {
        long startTime = System.currentTimeMillis();
        FileInputStream inputStream = null;// 读
        FileOutputStream outputStream = null;// 写

        String sourcePath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "test.mp3";
        String targetPath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "testCopy.mp3";

        try {
            File sourceFile = new File(sourcePath);
            File targetFile = new File(targetPath);
            if (targetFile.exists()) {
                targetFile.delete();
                targetFile.createNewFile();
            }

            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(targetFile);
            double sourceLength = inputStream.available();
            Log.i("==--", " 大小: " + sourceLength);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
                /*double left = inputStream.available();
                final int percent = (int) (((sourceLength - left) / sourceLength) * 100);

                if (lastPercent != percent) {
                    getWindow().getDecorView().post(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("==--", " 写大小: " + percent);
                            mPbTest.setProgress(percent);
                        }
                    });
                }
                lastPercent = percent;*/
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }


    /**
     * 利用缓冲流
     */
    private long copyFileByBufferStream() {
        long startTime = System.currentTimeMillis();
        FileInputStream inputStream;// 读
        FileOutputStream outputStream;// 写
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        String sourcePath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "test.mp3";
        String targetPath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "testCopy.mp3";

        try {
            File sourceFile = new File(sourcePath);
            File targetFile = new File(targetPath);
            if (targetFile.exists()) {
                targetFile.delete();
                targetFile.createNewFile();
            }

            inputStream = new FileInputStream(sourceFile);
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = new FileOutputStream(targetFile);
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            double sourceLength = inputStream.available();
            Log.i("==--", " 大小: " + sourceLength);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, length);
                double left = inputStream.available();
                final int percent = (int) (((sourceLength - left) / sourceLength) * 100);

                if (lastPercent != percent) {
                    getWindow().getDecorView().post(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("==--", " 写大小: " + percent);
                            mPbTest.setProgress(percent);
                        }
                    });
                }
                lastPercent = percent;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    /**
     * 利用FileChannel复制二进制文件
     */
    private long copyFileFileChannel() {
        long startTime = System.currentTimeMillis();
        FileInputStream inputStream = null;// 读
        FileOutputStream outputStream = null;// 写
        String sourcePath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "test.mp3";
        String targetPath = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + "testCopy.mp3";
        try {
            File sourceFile = new File(sourcePath);
            File targetFile = new File(targetPath);
            if (targetFile.exists()) {
                targetFile.delete();
                targetFile.createNewFile();
            }
            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(targetFile);
            FileChannel inChannel = inputStream.getChannel();
            WritableByteChannel outChannel = outputStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inChannel.size();
            inChannel.close();
            outChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

}
